//
//  MartinsNewInputView.m
//  NLProjectFrameworkDemo
//
//  Created by iosdeveloper on 2020/4/24.
//  Copyright © 2020 yj_zhang. All rights reserved.
//

#import "MartinsNewInputView.h"
#import "CommonHeader.h"
#import "NSString+Mantis.h"
@interface MartinsNewInputView()
@property(nonatomic,strong)UIColor*sendBtnDeepColor;
@property(nonatomic,strong)MatinsIMinitModel *configModel;
@end

@implementation MartinsNewInputView
-(instancetype)initWithFrame:(CGRect)frame{
    self=[super initWithFrame:frame];
    if (self) {
        self.backgroundColor =[UIColor whiteColor];
        [self setUpView];
    }
    return self;
}

-(void)setUpView{
    
    self.showLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 30, self.jk_width-20, 150)];
    self.showLabel.backgroundColor=[UIColor whiteColor];
    self.showLabel.text=@"可爱";
    self.showLabel.font =[UIFont systemFontOfSize:16];
    self.showLabel.numberOfLines=0;
    [self addSubview:self.showLabel];
    self.showLabel.hidden=YES;
    

     self.inputView=[UIView new];
     self.inputView.backgroundColor=[UIColor whiteColor];
    [self addSubview:self.inputView];
    
    [self.inputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    _faceBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    //chat_biao_icon
       [_faceBtn setImage:[UIImage imageNamed:@"chat_biao_icon"] forState:UIControlStateNormal];
       [_faceBtn setImage:[UIImage imageNamed:@"wzbj_jp_unselect"] forState:UIControlStateSelected];
       
       [_faceBtn addTarget:self action:@selector(faceBtnClick:) forControlEvents:UIControlEventTouchUpInside];
       [self.inputView addSubview:_faceBtn];
    
    [self.faceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
           make.centerY.equalTo(self);
           make.left.mas_equalTo(leftMantisMargin);
           make.width.height.mas_equalTo(adaptWidth750(48*0.7));
       }];
    
    self.imgBtn=[UIButton new];
    [self.imgBtn setImage:[UIImage imageNamed:@"chat_pic_icon"] forState:UIControlStateNormal];
    [self.imgBtn addTarget:self action:@selector(chosePhotoAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.inputView addSubview:self.imgBtn];
    [self.imgBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.faceBtn);
        make.left.mas_equalTo(self.faceBtn.mas_right).offset(leftMantisMargin);
    }];
    
    CGFloat textWidth=adaptWidth750(201*2);
    CGFloat textHeight=adaptWidth750(36*2);
    
    self.textField=[ZZEmojiTextView new];
     self.textField.delegate=self;
     self.textField.placeHolderLabel.text=@"请输入内容";
     self.textField.showsVerticalScrollIndicator=NO;
     self.textField.backgroundColor=kDefaultBgColor;
    self.textField.font =[UIFont systemFontOfSize:16];
     self.textField.layoutManager.allowsNonContiguousLayout = NO;//解决抖动问题
     [self.inputView addSubview:self.textField];
    
    WS(weakSelf);
    self.textField.faceBlock = ^(NSAttributedString *attributedStr) {
        weakSelf.textField.font =[UIFont systemFontOfSize:16];
        NSInteger length=attributedStr.length;
        weakSelf.sendBtn.backgroundColor=length>0?weakSelf.sendBtnDeepColor:senBtnGrayColor;
         weakSelf.sendBtn.userInteractionEnabled=length>0?YES:NO;
    };
    
    
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
           make.centerY.equalTo(self.faceBtn);
           make.left.mas_equalTo(self.imgBtn.mas_right).offset(leftMantisSpace);
           make.width.mas_equalTo(textWidth);
           make.height.mas_equalTo(textHeight);
       }];
    

    self.sendBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    self.sendBtn.backgroundColor=senBtnGrayColor;
    [self.sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [self.sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.sendBtn.titleLabel.font=KIMFontMedium(14);
    [self.sendBtn addTarget:self action:@selector(sendBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.sendBtn.contentMode=UIViewContentModeLeft;
    [self.inputView addSubview:self.sendBtn];
    [self.sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.faceBtn);
        make.left.mas_equalTo(self.textField.mas_right).offset(leftMantisSpace);
        make.width.mas_equalTo(adaptWidth750(61*2));
        make.height.equalTo(self.textField);
        
    }];

    ViewRadius(self.sendBtn, adaptWidth750(6*0.7));
}


-(void)sendBtnClick
{
  
    NSLog(@"plan%@",self.textField.plainString);
    NSString*richStr = [self changeEmojiMessage:self.textField.plainString];
    richStr=[richStr stringByReplacingOccurrencesOfString:@"\"" withString:@"'"];
     !self.callBackStr?:self.callBackStr(richStr);
    
}
//把[emoj]表情转为图片
-(NSMutableAttributedString*)changeMessage:(NSString *)str
{

    NSString * path = [[NSBundle mainBundle]pathForResource:@"MantisExpression" ofType:@"plist"];
    NSDictionary *emojiDict =[[NSDictionary alloc]initWithContentsOfFile:path];

    float height=  _showLabel.font.lineHeight;
  NSMutableAttributedString * mainAttr =[[NSMutableAttributedString alloc]initWithString:str];
    
    //通过正则表达式 判断是否 含有特定字符
    NSString*patternStr=@"\\[em:[0-9]*\\]";
    NSRegularExpression *regex=[NSRegularExpression regularExpressionWithPattern:patternStr options:NSRegularExpressionAnchorsMatchLines error:nil];
    __block NSUInteger location=0;
    
    
    NSArray *matches=[regex matchesInString:str options:NSMatchingWithoutAnchoringBounds range:NSMakeRange(0, str.length)];
    
    if (matches.count>0) {
        NSRange range={0,str.length};
        [regex enumerateMatchesInString:str options:NSMatchingWithTransparentBounds range:range usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
            //将特定字符 替换为 图片
            NSRange matchRange=[result range];
            NSString *subStr=[str substringWithRange:matchRange];
            
            NSTextAttachment *attachemnt=[[NSTextAttachment alloc]init];
            attachemnt.bounds=CGRectMake(0, -4, height, height);
            attachemnt.image=[UIImage imageNamed:emojiDict[subStr]];
            NSAttributedString *imageString=[NSAttributedString attributedStringWithAttachment:attachemnt];
            
            NSRange newRange={matchRange.location-location,matchRange.length};
            [mainAttr replaceCharactersInRange:newRange withAttributedString:imageString];
            location=location+matchRange.length-1;
            
            
        }];
        
    }
   
    return mainAttr;
    
}
//把表情字符串替换为<>标签字符串
-(NSString*)changeEmojiMessage:(NSString *)str
{
    

    NSString * path = [[NSBundle mainBundle]pathForResource:@"MantisEmojDiv" ofType:@"plist"];
    NSDictionary *emojiDict =[[NSDictionary alloc]initWithContentsOfFile:path];

    float height=  _showLabel.font.lineHeight;

    
    //通过正则表达式 判断是否 含有特定字符
    NSString*patternStr=@"\\[em:[0-9]*\\]";
    NSRegularExpression *regex=[NSRegularExpression regularExpressionWithPattern:patternStr options:NSRegularExpressionAnchorsMatchLines error:nil];
    __block NSUInteger location=0;
    
    __block NSString*mainAttr=str;
    NSArray *matches=[regex matchesInString:str options:NSMatchingWithoutAnchoringBounds range:NSMakeRange(0, str.length)];
    
    if (matches.count>0) {
        NSRange range={0,str.length};
        [regex enumerateMatchesInString:str options:NSMatchingWithTransparentBounds range:range usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
            //将特定字符 替换为 图片
            NSRange matchRange=[result range];
            NSString *subStr=[str substringWithRange:matchRange];
            
//            NSTextAttachment *attachemnt=[[NSTextAttachment alloc]init];
//            attachemnt.bounds=CGRectMake(0, -4, height, height);
//            attachemnt.image=[UIImage imageNamed:emojiDict[subStr]];
            NSString *imageString=emojiDict[subStr];
            
           // NSRange newRange={matchRange.location-location,matchRange.length};
           // [mainAttr replaceCharactersInRange:newRange withAttributedString:imageString];
          
       // [mainAttr stringByReplacingCharactersInRange:newRange withString:imageString];
        mainAttr=   [mainAttr stringByReplacingOccurrencesOfString:subStr withString:imageString];
            
            location=location+matchRange.length-1;
            
            
        }];
        
    }
   
    return mainAttr;
    
}

//把后台拿到的src资源转为图片
-(NSMutableAttributedString*)getEmojiMessage:(NSString *)str
{
   str=[str stringByReplacingOccurrencesOfString:@" >" withString:@">"];
   str=[str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    str=[str stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
    NSString * path = [[NSBundle mainBundle]pathForResource:@"MantisEmojScr" ofType:@"plist"];
    NSDictionary *emojiDict =[[NSDictionary alloc]initWithContentsOfFile:path];

    float height=  _showLabel.font.lineHeight;
  NSMutableAttributedString * mainAttr =[[NSMutableAttributedString alloc]initWithString:str];
  
    //通过正则表达式 判断是否 含有特定字符
    NSString*patternStr=@"<(img|IMG)(.*?)(/>|></img>|>)";
    NSRegularExpression *regex=[NSRegularExpression regularExpressionWithPattern:patternStr options:NSRegularExpressionCaseInsensitive error:nil];
    __block NSUInteger location=0;
    
    
    NSArray *matches=[regex matchesInString:str options:NSMatchingWithoutAnchoringBounds range:NSMakeRange(0, str.length)];
    
    if (matches.count>0) {
        NSRange range={0,str.length};
        [regex enumerateMatchesInString:str options:NSMatchingWithTransparentBounds range:range usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
            //将特定字符 替换为 图片
            NSRange matchRange=[result range];
            NSString *subStr=[str substringWithRange:matchRange];
            
            NSTextAttachment *attachemnt=[[NSTextAttachment alloc]init];
            attachemnt.bounds=CGRectMake(0, -4, height, height);
            attachemnt.image=[UIImage imageNamed:emojiDict[subStr]];
            NSAttributedString *imageString=[NSAttributedString attributedStringWithAttachment:attachemnt];
            
            NSRange newRange={matchRange.location-location,matchRange.length};
            [mainAttr replaceCharactersInRange:newRange withAttributedString:imageString];
            location=location+matchRange.length-1;
            
            
        }];
        
    }
   
    return mainAttr;
    
}

//把后台拿到的src资源转为图片
-(NSString*)getEmojiMessageStr:(NSString *)str
{

    str =[str stringByReplacingOccurrencesOfString:@" >" withString:@">"];
     str =[str stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
    NSString * path = [[NSBundle mainBundle]pathForResource:@"MantisEmojScr" ofType:@"plist"];
    NSDictionary *emojiDict =[[NSDictionary alloc]initWithContentsOfFile:path];

    float height=  _showLabel.font.lineHeight;
 
  
    //通过正则表达式 判断是否 含有特定字符
    NSString*patternStr=@"<(img|IMG)(.*?)(/>|></img>|>)";
    NSRegularExpression *regex=[NSRegularExpression regularExpressionWithPattern:patternStr options:NSRegularExpressionCaseInsensitive error:nil];
    __block NSUInteger location=0;
    
     __block NSString*mainAttr=str;
    NSArray *matches=[regex matchesInString:str options:NSMatchingWithoutAnchoringBounds range:NSMakeRange(0, str.length)];
    
    if (matches.count>0) {
        NSRange range={0,str.length};
        [regex enumerateMatchesInString:str options:NSMatchingWithTransparentBounds range:range usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
            //将特定字符 替换为 图片
            NSRange matchRange=[result range];
            NSString *subStr=[str substringWithRange:matchRange];
            
            NSString *imageString=emojiDict[subStr];
            if ([NSString isBlankString:imageString]) {
               mainAttr=   [mainAttr stringByReplacingOccurrencesOfString:subStr withString:@""];
            }else{
                mainAttr=   [mainAttr stringByReplacingOccurrencesOfString:subStr withString:imageString];
            }
           
            location=location+matchRange.length-1;
        }];
        
    }
   
    return mainAttr;
    
}



-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.textField resignFirstResponder];
}
-(void)faceBtnClick:(UIButton *)btn
{
    [self.textField resignFirstResponder];
    btn.selected=!btn.selected;
    [self.textField changeKeyBoardType:btn.isSelected?KeyBoardFace:KeyBoardSystem];
}

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{
  //  [self.textField setContentOffset:CGPointZero animated:NO];
    return  YES;
}
-(void)textViewDidBeginEditing:(UITextView *)textView{
    self.textField.placeHolderLabel.hidden=YES;
    [[NSNotificationCenter defaultCenter]postNotificationName:kuserStartInputNotice object:nil];
}


-(void)textViewDidChange:(UITextView *)textView{
   
    NSInteger length =textView.text.length;

    self.sendBtn.backgroundColor=length>0?self.sendBtnDeepColor:senBtnGrayColor;
    self.sendBtn.userInteractionEnabled=length>0?YES:NO;
    
    [[NSNotificationCenter defaultCenter]postNotificationName:kuserDidInputNotice object:nil];
  
}

-(void)textViewDidEndEditing:(UITextView *)textView{
    
     [[NSNotificationCenter defaultCenter]postNotificationName:kuserEndInputNotice object:nil];
}




-(void)chosePhotoAction:(UIButton*)sennder{
    
    !self.photoBlock?:self.photoBlock();
}

-(void)clearAllText:(MartinsNewInputView*)inputView{
    inputView.textField.text=@"";
    NSInteger length = inputView.textField.text.length;
    
    self.sendBtn.backgroundColor=length>0?self.sendBtnDeepColor:senBtnGrayColor;
    self.sendBtn.userInteractionEnabled=length>0?YES:NO;
    
}


-(void)reloadSendView:(MatinsIMinitModel *)model{
    self.configModel=model;

}

-(UIColor *)sendBtnDeepColor{
    UIColor*btnColor =KAppMainColor;
    if (self.configModel.mbSndBtnColor.length>0) {
        btnColor=[UIColor jk_colorWithHexString:self.configModel.mbSndBtnColor];
    }
    return  btnColor;;
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
